﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using ERP_RORZE_SYSTEM;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace ERP_RORZE_DLL.Business
{
    public partial class panel_MasterPODetails : UserControl
    {
        private INISettings mySetting;
        private SqlConnection myConnection;

        public panel_MasterPODetails()
        {
            InitializeComponent();
            mySetting = new INISettings();
            myConnection = new SqlConnection(mySetting.SQLConnectionString);
            LoadData();
            this.MasterPODetails.PopupMenuShowing += MasterPODetails_PopupMenuShowing;
            this.masterPODetailcontextMenu.ItemClicked += masterPODetailcontextMenu_ItemClicked;

            this.MasterPODetails.DoubleClick += MasterPODetails_DoubleClick;
        }

        void MasterPODetails_DoubleClick(object sender, EventArgs e)
        {
            callEditForm();
        }

        // Call Edit Form
        private void callEditForm()
        {
            DataRow row = this.MasterPODetails.GetFocusedDataRow();
            if ((bool)row["Cancelled"])
            {
                MessageBox.Show("This Order has been cancelled");
            }
            else
            {
                frm_Edit_MasterPODetails edit_form = new frm_Edit_MasterPODetails();
                edit_form.poid = row["POID"].ToString();
                edit_form.order = row["OrderNo"].ToString();
                if (edit_form.LoadData())
                {
                    edit_form.ShowDialog();
                    LoadData();
                }
                else
                {
                    MessageBox.Show("Cannot edit selected record. Please try again");
                }
            }
        }

        void masterPODetailcontextMenu_ItemClicked(object sender, ToolStripItemClickedEventArgs e)
        {
            this.masterPODetailcontextMenu.Hide();            
            switch (e.ClickedItem.Name)
            {
                case "editSelection":
                    callEditForm();
                    break;
                case "cancelSelection":
                    callCancelFunction();
                    break;
                case "addSelection":
                    frm_Add_MasterPODetails add_Form = new frm_Add_MasterPODetails();
                    add_Form.ShowDialog();
                    LoadData();
                    break;
                case "refreshSelection":
                    LoadData();
                    break;
            }
        }

        //////////////////////////
        /// Call Cancel Function
        ///////////////////////////
        private void callCancelFunction()
        {
            DataRow row = this.MasterPODetails.GetFocusedDataRow();
            cancelOrderPODetails(row["OrderNo"].ToString(), row["POID"].ToString());
            LoadData();
        }

        void MasterPODetails_PopupMenuShowing(object sender, DevExpress.XtraGrid.Views.Grid.PopupMenuShowingEventArgs e)
        {
            this.masterPODetailcontextMenu.Show(MousePosition);            
        }       

        private void buttonAdd_Click(object sender, EventArgs e)
        {
            frm_Add_MasterPODetails add_Form = new frm_Add_MasterPODetails();
            add_Form.ShowDialog();
            LoadData();
        }

        
        /////////////////////////////////
        /// Load POdetails into gridview
        /////////////////////////////////
        private void LoadData()
        {            
            DataSet sourceDataSet = new DataSet();
            SQLManagement mySQLManagement = new SQLManagement();
            mySQLManagement.SQLConnectionString = mySetting.SQLConnectionString;
            string sql = "SELECT t1.POID, t3.SupplierName, t1.OrderNo, t1.PartNo,"
                + " t1.Quantity, t1.UnitID, t1.UnitPrice, t1.CurrencyID,"
                + " t1.DeliveryDate, t4.TransportName, t5.DeliveryTermName,"
                + " t7.UnitID AS IQUnit, t6.[Using/IQEx] AS UnitExchange, t1.Purpose, t6.Remark AS [Note], t1.Change,"
                + " t1.Finished, t1.Cancelled"
                + " FROM [241_MasterPODetails] AS t1"
                + " LEFT JOIN [241_MasterPO] AS t2 ON t1.POID = t2.ID"
                + " LEFT JOIN [222_Supplier] AS t3 ON t2.SupplierID = t3.SupplierID"
                + " LEFT JOIN [222_Transport] AS t4 ON t1.TransportID=t4.TransportID"
                + " LEFT JOIN [222_DeliveryTerm] AS t5 ON t1.DeliveryTermID=t5.DeliveryTermID"
                + " LEFT JOIN [222_Part] AS t6 ON t1.PartNo = t6.PartNo"
                + " LEFT JOIN [222_IQ] AS t7 ON t6.IQID = t7.IQID"
                + " ORDER BY SUBSTRING(t1.POID, 5, 6) DESC";
            sourceDataSet = mySQLManagement.SQL_Query(sql);
            if (sourceDataSet != null)
            {
                gridMasterPODetails.DataSource = sourceDataSet.Tables[0];
            }
            else
            {
                DataTable newTable = new DataTable();
                newTable.Columns.Add("PO ID", typeof(string));
                newTable.Columns.Add("SupplierName", typeof(string));
                newTable.Columns.Add("OrderNo", typeof(string));
                newTable.Columns.Add("PartNo", typeof(string));
                newTable.Columns.Add("Quantity", typeof(int));
                newTable.Columns.Add("UnitID", typeof(string));
                newTable.Columns.Add("UnitPrice", typeof(float));
                newTable.Columns.Add("Currency", typeof(string));
                newTable.Columns.Add("DeliveryDate", typeof(DateTime));
                newTable.Columns.Add("TransportID", typeof(string));
                newTable.Columns.Add("DeliveryTermID", typeof(string));
                newTable.Columns.Add("IQUnit", typeof(string));
                newTable.Columns.Add("UnitExchange", typeof(int));
                newTable.Columns.Add("Purpose", typeof(string));
                newTable.Columns.Add("Note", typeof(string));
                newTable.Columns.Add("Change", typeof(bool));
                newTable.Columns.Add("Finished", typeof(bool));
                newTable.Columns.Add("Cancelled", typeof(bool));
                gridMasterPODetails.DataSource = newTable;
            }
            MasterPODetails.Columns[0].Caption = "PO ID";
            MasterPODetails.Columns[1].Caption = "Supplier Name";
            MasterPODetails.Columns[2].Caption = "Order No";
            MasterPODetails.Columns[3].Caption = "Part No";
            MasterPODetails.Columns[4].Caption = "Quantity";
            MasterPODetails.Columns[5].Caption = "Unit";
            MasterPODetails.Columns[6].Caption = "Unit Price";
            MasterPODetails.Columns[7].Caption = "Currency";
            MasterPODetails.Columns[8].Caption = "Delivery Date";
            MasterPODetails.Columns[9].Caption = "Transpor ID";
            MasterPODetails.Columns[10].Caption = "Delivery Term ID";
            MasterPODetails.Columns[11].Caption = "IQUnit";
            MasterPODetails.Columns[12].Caption = "UnitID/IQUnit";
            MasterPODetails.Columns[13].Caption = "Purpose";
            MasterPODetails.Columns[14].Caption = "Note";
            MasterPODetails.Columns[15].Caption = "Change";
            MasterPODetails.Columns[16].Caption = "Finished";
            MasterPODetails.Columns[17].Caption = "Cancelled";
            MasterPODetails.BestFitColumns();
        }

        /////////////////////////////////////////////////////
        /// Cancel OrderNo in PODetails
        /////////////////////////////////////////////////////
        private void cancelOrderPODetails(string orderno, string poid)
        {
            if (MessageBox.Show("Really cancel?", "Confirm cancel", MessageBoxButtons.YesNo) == DialogResult.Yes)
            {
                try
                {
                    myConnection.Open();
                    SqlCommand cmd_sql = myConnection.CreateCommand();
                    cmd_sql.CommandText = "UPDATE [241_MasterPODetails] SET Cancelled=1"
                        + " WHERE OrderNo='" + orderno + "' AND POID='" + poid + "' AND Cancelled=0";
                    cmd_sql.ExecuteNonQuery();
                    cmd_sql.Dispose();
                    myConnection.Close();
                    MessageBox.Show("The OrderNo " + orderno + " of POID " + poid + " has been canceled successfully.");
                }
                catch
                {
                    if (myConnection.State == ConnectionState.Open)
                    {
                        myConnection.Close();
                    }
                    MessageBox.Show("Cannot cancel the OrderNo " + orderno + " of POID " + poid + ". Please try again.");
                }
            }
        }
        
        private void buttonCancel_Click(object sender, EventArgs e)
        {
            callCancelFunction();
        }

        private void buttonEdit_Click(object sender, EventArgs e)
        {
            callEditForm();
        }

        private void buttonRefresh_Click(object sender, EventArgs e)
        {
            LoadData();
        }
    }
}
